package com.kids.movies.view;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.englishsong.nurseryrhymes.R;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.AdView;
import com.ironsource.mobilcore.CallbackResponse;
import com.ironsource.mobilcore.MobileCore;
import com.ironsource.mobilcore.MobileCore.LOG_TYPE;
import com.kids.movies.E4KidsConfig;
import com.kids.movies.E4KidsSlidingMenuActivity;
import com.kids.movies.adapter.DetailVideoPagerAdapter;
import com.kids.movies.fragment.IndexFragment;
import com.kids.movies.fragment.IndexNewFreagment;
import com.kids.movies.fragment.IndexViewFragment;
import com.kids.movies.util.Debug;
import com.kids.movies.util.TabFactory;

public class IndexActivity extends E4KidsSlidingMenuActivity implements
		OnTabChangeListener, OnPageChangeListener, OnClickListener {
	private TabHost mTabHost;
	private ViewPager pager;

	private ImageView ivABCancelSearch;
	private ImageView ivABSearch;
	private EditText edtABSearch;
	private LinearLayout llContainEdt;
	private TextView tvABTitle;
	private ImageView ivABLogo;
	private ImageView ivShare;
	private AdView adView;
//	private ImageView ivCloseAds;
	private RelativeLayout rlContainAds;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_index);

		this.setBehindContentView(R.layout.frame_layout_container);
		// this.getSlidingMenu().setSecondaryMenu(R.layout.frame_right_container);
		this.setDefaultBar();
		configLeftSlideMenu();
		// this.removeSlidingMenu();

		init();

		List<Fragment> listFragments = new ArrayList<Fragment>();

		listFragments.add(new IndexFragment());
		listFragments.add(new IndexNewFreagment());
		listFragments.add(new IndexViewFragment());
		DetailVideoPagerAdapter adapter = new DetailVideoPagerAdapter(
				IndexActivity.this, getSupportFragmentManager(), listFragments);

		pager.setAdapter(adapter);
		pager.setOffscreenPageLimit(2);
		pager.setOnPageChangeListener(this);

	}

	private void init() {
		adView = (AdView) findViewById(R.id.ad);
//		ivCloseAds = (ImageView) findViewById(R.id.ivCloseAds);
		rlContainAds = (RelativeLayout) findViewById(R.id.rlContainAds);

//		ivCloseAds.setOnClickListener(this);

		adView.setAdListener(new AdListener() {
			@Override
			public void onReceiveAd(Ad arg0) {
				Debug.debug("onReceiveAd");

				if (adView.getVisibility() == View.VISIBLE) {
//					ivCloseAds.setVisibility(View.VISIBLE);
					rlContainAds.setVisibility(View.VISIBLE);
				} else {
//					ivCloseAds.setVisibility(View.GONE);
					rlContainAds.setVisibility(View.GONE);
				}
			}

			@Override
			public void onPresentScreen(Ad arg0) {
				Debug.debug("onPresentScreen");
			}

			@Override
			public void onLeaveApplication(Ad arg0) {
				Debug.debug("onLeaveApplication");
			}

			@Override
			public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
				Debug.debug("onFailedToReceiveAd");
//				ivCloseAds.setVisibility(View.GONE);
			}

			@Override
			public void onDismissScreen(Ad arg0) {
				Debug.debug("onDismissScreen");
			}
		});

		ivABCancelSearch = actionBar.getIvABCancelSearch();
		ivABSearch = actionBar.getIvABSearch();
		edtABSearch = actionBar.getEdtABSearch();
		llContainEdt = actionBar.getLlContainEdt();
		ivABLogo = actionBar.getIvABLogo();
		tvABTitle = actionBar.getTvABTitle();
		ivShare = actionBar.getIvShare();

		ivShare.setOnClickListener(this);

		ivABLogo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				toggle();
			}
		});

		// edtABSearch.setOnEditorActionListener(searchAction);
		ivABSearch.setOnClickListener(this);
		ivABCancelSearch.setOnClickListener(this);

		edtABSearch.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
		edtABSearch.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView arg0, int actionID,
					KeyEvent arg2) {
				// RequestUrlService.requestSearchNameSinger(delegateSinger,
				// "tuan hung");
				String text = edtABSearch.getText().toString().trim();
				if (!text.equals("") || !TextUtils.isEmpty(text)) {

					goActivitySearch(IndexActivity.this,
							SearchResultActivity.class,
							E4KidsConfig.KEY_INTENT_SEARCH, text);
				}
				return true;
			}
		});

		mTabHost = (TabHost) findViewById(android.R.id.tabhost);
		mTabHost.setOnTabChangedListener(this);
		pager = (ViewPager) findViewById(R.id.cate_info_pager);

		mTabHost.setup();
		addTab();
	}

	private void addTab() {
		View tabIndicator = LayoutInflater.from(IndexActivity.this).inflate(
				R.layout.tab_tabhost, mTabHost.getTabWidget(), false);
		View tabIndicator1 = LayoutInflater.from(IndexActivity.this).inflate(
				R.layout.tab_tabhost, mTabHost.getTabWidget(), false);
		View tabIndicator2 = LayoutInflater.from(IndexActivity.this).inflate(
				R.layout.tab_tabhost, mTabHost.getTabWidget(), false);
		TextView tvNew = (TextView) tabIndicator.findViewById(R.id.title);
		TextView tvIndex = (TextView) tabIndicator1.findViewById(R.id.title);
		TextView tvlike = (TextView) tabIndicator2.findViewById(R.id.title);

		tvNew.setText(getString(R.string.tab_new));
		tvIndex.setText(getString(R.string.tab_home));
		tvlike.setText(getString(R.string.tab_view));

		TabHost.TabSpec tSpecIndex = mTabHost
				.newTabSpec(getString(R.string.tab_home));
		tSpecIndex.setIndicator(tabIndicator1);
		tSpecIndex.setContent(new TabFactory(IndexActivity.this));
		mTabHost.addTab(tSpecIndex);

		TabHost.TabSpec tSpecNew = mTabHost
				.newTabSpec(getString(R.string.tab_new));
		tSpecNew.setIndicator(tabIndicator);

		tSpecNew.setContent(new TabFactory(IndexActivity.this));
		mTabHost.addTab(tSpecNew);

		TabHost.TabSpec tSpecLike = mTabHost
				.newTabSpec(getString(R.string.tab_view));
		tSpecLike.setIndicator(tabIndicator2);
		tSpecLike.setContent(new TabFactory(IndexActivity.this));
		mTabHost.addTab(tSpecLike);

	}

	@Override
	public void onTabChanged(String arg0) {
		int pos = this.mTabHost.getCurrentTab();
		this.pager.setCurrentItem(pos);
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	@Override
	public void onPageSelected(int arg0) {
		if (arg0 == 0) {
			enableSlidingMenu();
		} else {
			this.removeSlidingMenu();
		}
		this.mTabHost.setCurrentTab(arg0);
	}

	private void showDialog() {

		if (dialog == null) {
			dialog = new Dialog(IndexActivity.this);
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		}

		dialog.setCancelable(true);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setContentView(R.layout.layout_exit);

		Button btLeft = (Button) dialog.findViewById(R.id.btExitLeft);
		Button btRight = (Button) dialog.findViewById(R.id.btExitRight);
		Button btCenter = (Button) dialog.findViewById(R.id.btExitCenter);
		Button btIntentApp = (Button) dialog.findViewById(R.id.btIntentApp);
		// Button btDownload = (Button) dialog.findViewById(R.id.btDownload);
		// Button btSkip = (Button) dialog.findViewById(R.id.btSkip);
		final LinearLayout llLstAds = (LinearLayout) dialog
				.findViewById(R.id.llAds);
		JSONArray jArrLstAds = app.getjArrAdsExit();
		int lengthAds = jArrLstAds.length();
		for (int i = 0; i < lengthAds; i++) {
			try {
				JSONObject jObjDetailAds = jArrLstAds.getJSONObject(i);

				LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				View vAds = mInflater.inflate(R.layout.layout_banner_my_ads,
						null);

				ImageView ivAvatar = (ImageView) vAds.findViewById(R.id.ivAds);
				TextView tvNameAds = (TextView) vAds
						.findViewById(R.id.tvNameAds);
				TextView tvContentAds = (TextView) vAds
						.findViewById(R.id.tvContentAds);
				final LinearLayout llMyads = (LinearLayout) vAds
						.findViewById(R.id.llMyads);

				Button btDownloadAds = (Button) vAds
						.findViewById(R.id.btDownload);
				Button btSkip = (Button) vAds.findViewById(R.id.btSkip);

				String linkImage = jObjDetailAds.getString("image");
				String name = jObjDetailAds.getString("title");
				String content = jObjDetailAds.getString("content");
				final String linkMarket = jObjDetailAds.getString("link");

				tvNameAds.setText(name);
				tvContentAds.setText(content);

				imageLoader.displayImage(linkImage, ivAvatar, options);

				btDownloadAds.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {

						String packageName = linkMarket;
						try {
							StringBuilder strb = new StringBuilder();
							strb.append("market://details?id=").append(
									packageName);
							Debug.debug("Market : " + strb.toString());

							Intent intent = new Intent(Intent.ACTION_VIEW);
							intent.setData(Uri.parse(strb.toString()));
							startActivity(intent);
						} catch (ActivityNotFoundException activityNotFound) {
							// to handle play store not installed scenario
							Intent intent = new Intent(
									Intent.ACTION_VIEW,
									Uri.parse("http://play.google.com/store/apps/details?id="
											+ packageName));
							startActivity(intent);
						}

					}
				});

				btSkip.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						llMyads.setVisibility(View.GONE);
					}
				});

				llLstAds.addView(vAds, i);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		dialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface arg0) {
				MobileCore.showOfferWall(IndexActivity.this,
						new CallbackResponse() {
							@Override
							public void onConfirmation(TYPE arg0) {
								hidenDialog();
								// showDialog();
							}
						});
				// hidenDialog();
			}
		});

		btRight.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

			}
		});

		btIntentApp.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				try {
					StringBuilder strb = new StringBuilder();
					strb.append("market://search?q=pub:Edukidsvn");
					Debug.debug("Market : " + strb.toString());

					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setData(Uri.parse(strb.toString()));
					startActivity(intent);
				} catch (ActivityNotFoundException activityNotFound) {
					// to handle play store not installed scenario
					Intent intent = new Intent(
							Intent.ACTION_VIEW,
							Uri.parse("http://play.google.com/store/search?q=pub:Edukidsvn"));
					startActivity(intent);
				}

			}
		});

		btLeft.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				hidenDialog();
				// onBackPressed();
				IndexActivity.this.finish();
			}
		});

		btCenter.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						String packageName = getApplicationContext()
								.getPackageName();
						try {
							StringBuilder strb = new StringBuilder();
							strb.append("market://details?id=").append(
									packageName);
							Debug.debug("Market : " + strb.toString());

							Intent intent = new Intent(Intent.ACTION_VIEW);
							intent.setData(Uri.parse(strb.toString()));
							startActivity(intent);
						} catch (ActivityNotFoundException activityNotFound) {
							// to handle play store not installed scenario
							Intent intent = new Intent(
									Intent.ACTION_VIEW,
									Uri.parse("http://play.google.com/store/apps/details?id="
											+ packageName));
							startActivity(intent);
						}
					}
				});
			}
		});

		dialog.show();
	}

	private void hidenDialog() {
		if (dialog != null) {
			dialog.dismiss();
			dialog = null;
		}
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.iv_search:
			if (llContainEdt.getVisibility() == View.GONE) {
				llContainEdt.setVisibility(View.VISIBLE);
				ivABSearch.setVisibility(View.GONE);
				tvABTitle.setVisibility(View.GONE);
				edtABSearch.setFocusable(true);
				edtABSearch.requestFocus();
				showBoard(edtABSearch);
			}
			break;
		case R.id.iv_cancel:
			String text = edtABSearch.getText().toString().trim();
			if (!text.equals("")) {
				edtABSearch.setText("");
			} else {
				llContainEdt.setVisibility(View.GONE);
				ivABSearch.setVisibility(View.VISIBLE);
				tvABTitle.setVisibility(View.VISIBLE);
				edtABSearch.setFocusable(true);
				hiddenBoard(edtABSearch);
			}
			break;
//		case R.id.ivCloseAds:
//			rlContainAds.setVisibility(View.GONE);
//			break;
		case R.id.ivShare:
			shareTextUrl(packageName);
		}

	}

	@Override
	public void onBackPressed() {
		finish();
//		MobileCore.init(this, E4KidsConfig.MOBICORE, LOG_TYPE.PRODUCTION);
//		MobileCore.showOfferWall(IndexActivity.this, new CallbackResponse() {
//			@Override
//			public void onConfirmation(TYPE arg0) {
//				IndexActivity.this.finish();
//			}
//		});

	}
}
